package com.cc8w.handler;


import org.apache.ibatis.executor.result.ResultMapException;
import org.apache.ibatis.type.DateTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.*;
import java.util.Date;

/**
 * @author tianyuting
 * @date 2019/11/110:59
 */
//@MappedJdbcTypes({JdbcType.DATE,JdbcType.TIMESTAMP}) 这个注解在一开始是没有加的。如果不加需要在mapper.xml中使用typeHandler="" 进行引用
public class MyDateTypeHandler extends DateTypeHandler {

    @Override
    public Date getResult(ResultSet rs, String columnName) throws SQLException {
        Date result;
        try {
            result = getNullableResult(rs, columnName);
        } catch (Exception e) {
            throw new ResultMapException("Error attempting to get column '" + columnName + "' from result set.  Cause: " + e, e);
        }
        return result;

    }

    @Override
    public Date getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        Timestamp sqlTimestamp = rs.getTimestamp(columnName);
        if (sqlTimestamp != null) {
//            throw new SimpleException("fffff");
            return new Date(sqlTimestamp.getTime());
        }
        return new Date(0);
    }

    @Override
    public Date getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        Timestamp sqlTimestamp = rs.getTimestamp(columnIndex);
        if (sqlTimestamp != null) {
            return new Date(sqlTimestamp.getTime());
        }
        return new Date(0);
    }

    @Override
    public Date getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        Timestamp sqlTimestamp = cs.getTimestamp(columnIndex);
        if (sqlTimestamp != null) {
            return new Date(sqlTimestamp.getTime());
        }
        return new Date(0);
    }
}